<template>
  <div class="c-width c-flex c-dis-flex-col com_tree_right_bg  c-hidden">
    <el-form class="c-flex c-scroll-y"  :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">
      <el-form-item label="适用人员：" v-show="false">
        <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
        <el-checkbox v-model="deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="dept"
          node-key="id"
          :check-strictly="!deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
      <el-form-item label="试卷类型：" prop="paperType">
        <el-select v-model="form.paperType" placeholder="试卷类型">
          <el-option
            v-for="dict in dict.type.exam_paper_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间限制：" required v-show="form.paperType==2">
        <el-date-picker v-model="form.limitDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="试卷名称：" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item :key="index" :label="'标题'+(index+1)+'：'" required v-for="(titleItem,index) in form.titleItems">
        <el-input v-model="titleItem.name" style="width: 80%"/>
        <el-button type="text" class="link-left" style="margin-left: 20px" size="mini" @click="addQuestion(titleItem)">
          添加题目
        </el-button>
        <el-button type="text" class="link-left" size="mini" @click="form.titleItems.splice(index,1)">删除</el-button>
        <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
          <el-form-item :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"
                        v-for="(questionItem,questionIndex) in titleItem.questionItems" style="margin-bottom: 15px">
            <el-row>
              <el-col :span="23">
                <QuestionShow :qType="questionItem.questionType" :question="questionItem"/>
              </el-col>
              <el-col :span="1">
                <el-button type="text" size="mini" @click="titleItem.questionItems.splice(questionIndex,1)">删除
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>
      </el-form-item>
      <el-form-item label="建议时长：" prop="suggestTime" required>
        <el-input v-model="form.suggestTime" placeholder="分钟"/>
      </el-form-item>
      <el-form-item label="合格分数：" prop="passScore" required>
        <el-input v-model="form.passScore" placeholder="合格分数"/>总分数:{{form.score}}
      </el-form-item>
    </el-form>
    <el-col :span="24" class="com_form_btn_center">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="resetForm">重 置</el-button>
      <el-button type="success" @click="addTitle">添加标题</el-button>
    </el-col>
    <!-- 添加题目 -->
    <el-dialog :visible.sync="questionPage.showDialog" width="70%" title="添加题目">
      <el-form :model="questionPage.queryParam" ref="queryForm" :inline="true">
        <el-form-item label="题目名称 ：">
          <el-input v-model="questionPage.queryParam.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="题型：">
          <el-select v-model="questionPage.queryParam.questionType" clearable>
            <el-option
              v-for="dict in dict.type.question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryForm">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="questionPage.listLoading" :data="questionPage.tableData"
                @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column prop="id" label="Id" width="60px" v-if="false"/>
        <el-table-column prop="questionType" label="题型" width="70px">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.question_type" :value="scope.row.questionType"/>
          </template>
        </el-table-column>

        <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip/>

        <el-table-column prop="createTime" label="录入时间" width="160px"/>
      </el-table>

      <pagination v-show="questionPage.total > 0" :total="questionPage.total"
                  :page.sync="questionPage.queryParam.pageNum"
                  :limit.sync="questionPage.queryParam.pageSize"
                  @pagination="search"
      />
      <span slot="footer" class="dialog-footer">
          <el-button @click="questionPage.showDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters, mapState, mapActions } from 'vuex'

import Pagination from '@/components/Pagination'
import QuestionShow from '../question/components/Show'
import { PaperEdit, PaperSelect } from '@/api/examPaper'
import { deptTreeSelect} from '@/api/exam/examManage'
import { QuePageList, QueSelect } from '@/api/question'

export default {
  components: { Pagination, QuestionShow },
  dicts: ['exam_paper_type','question_type'],
  data() {
    return {
      form: {
        id: null,
        level: null,
        subjectId: null,
        paperType: '1',
        limitDateTime: [],
        name: '',
        suggestTime: null,
        titleItems: []
      },
      subjectFilter: null,
      formLoading: false,
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      deptExpand: true,
      deptNodeAll: false,
      deptCheckStrictly: true,
      rules: {
        paperType: [
          { required: true, message: '请选择试卷类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
        suggestTime: [
          { required: true, message: '请输入建议时长', trigger: 'blur' }
        ]
      },
      questionPage: {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          id: null,
          questionType: null,
          pageNum: 1,
          pageSize: 10
        },
        listLoading: true,
        tableData: [],
        total: 0
      },
      currentTitleItem: null
    }
  },
  created() {
    let id = this.$route.query.id
    let _this = this
    // 获取树结构
    const deptTreeSelect = this.getDeptTree(1)

    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      PaperSelect(id).then(re => {
        _this.form = re.data
        console.log("_this.form :",_this.form );
        // 设置部门树
        this.$nextTick(() => {
          deptTreeSelect.then(res => {
            this.$refs.dept.setCheckedKeys([re.data.deptId])
          })
        })
        _this.formLoading = false
      })
    }
  },
  methods: {
    /** 根据角色ID查询部门树结构 */
    getDeptTree() {
      return deptTreeSelect(1).then(response => {
        this.deptOptions = response.depts
        return response
      })
    },

    submitForm() {
       let _this = this
       /*let deptIds = this.getDeptAllCheckedKeys()
        if (deptIds.length != 1) {
          _this.$message.error('请选择一个适用人员部门!')
          return
        }
        if (deptIds.length > 0) {
          this.form.deptId = deptIds.join(',')
        }*/
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true
          PaperEdit(this.form).then(re => {
            if (re.code === 200) {
              _this.$message.success(re.msg)
               _this.delCurrentView(_this).then(() => {
                 _this.$router.push('/practice/paper/list')
               })
            } else {
              _this.$message.error(re.msg)
              this.formLoading = false
            }
          }).catch(e => {
            this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    addTitle() {
      this.form.titleItems.push({
        name: '',
        questionItems: []
      })
    },
    addQuestion(titleItem) {
      this.questionPage= {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          id: null,
          questionType: null,
          pageNum: 1,
          pageSize: 10
        },
        listLoading: true,
        tableData: [],
        total: 0
      }
      this.currentTitleItem = titleItem
      this.questionPage.showDialog = true
      this.questionPage.queryParam.pageNum = 1
      this.search()
    },
    removeTitleItem(titleItem) {
      this.form.titleItems.remove(titleItem)
    },
    removeQuestion(titleItem, questionItem) {
      titleItem.questionItems.remove(questionItem)
    },
    queryForm() {
      this.questionPage.queryParam.pageNum = 1
      this.search()
    },
    confirmQuestionSelect() {
      let _this = this
      this.questionPage.multipleSelection.forEach(q => {
        QueSelect(q.id).then(re => {
          _this.currentTitleItem.questionItems.push(re.data)
        })
      })
      this.questionPage.showDialog = false
    },
    levelChange() {
      this.form.subjectId = null
      this.subjectFilter = this.subjects.filter(data => data.level === this.form.level)
    },
    search() {
      this.questionPage.listLoading = true
      QuePageList(this.questionPage.queryParam).then(data => {
        this.questionPage.tableData = data.rows
        console.log("data.total:",data.total);
        this.questionPage.total = data.total
        this.questionPage.listLoading = false
      })
    },
    handleSelectionChange(val) {
      this.questionPage.multipleSelection = val
    },
    questionTypeFormatter(row, column, cellValue, index) {
      return this.enumFormat(this.questionTypeEnum, cellValue)
    },
    subjectFormatter(row, column, cellValue, index) {
      return this.subjectEnumFormat(cellValue)
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false
      }
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的部门节点
      //let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      //checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys
    },
    resetForm() {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        id: null,
        level: null,
        subjectId: null,
        paperType: null,
        limitDateTime: [],
        name: '',
        suggestTime: null,
        titleItems: []
      }
      this.form.id = lastId
    },
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {}
}
</script>

<style lang="scss">
.exampaper-item-box {
  .q-title {
    margin: 0px 5px 0px 5px;
  }

  .q-item-content {
  }
}
</style>
